from sqlmodel import SQLModel, create_engine, Session
from core.Config import settings
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
from typing import AsyncGenerator

DB_BASE_TYPE = settings.DB_BASE_TYPE
DB_BASE_HOST = settings.DB_BASE_HOST
DB_BASE_PORT = settings.DB_BASE_PORT
DB_BASE_DBNAME = settings.DB_BASE_DBNAME
DB_BASE_USER = settings.DB_BASE_USER
DB_BASE_PASSWORD = settings.DB_BASE_PASSWORD
APP_DEBUG = settings.APP_DEBUG

# 构建数据库 URL
database_url = f"mysql+pymysql://{DB_BASE_USER}:{DB_BASE_PASSWORD}@{DB_BASE_HOST}:{DB_BASE_PORT}/{DB_BASE_DBNAME}"
engine = create_engine(database_url,echo=APP_DEBUG)

# 异步引擎
async_database_url = f"mysql+aiomysql://{DB_BASE_USER}:{DB_BASE_PASSWORD}@{DB_BASE_HOST}:{DB_BASE_PORT}/{DB_BASE_DBNAME}"
async_engine = create_async_engine(async_database_url, echo=APP_DEBUG)
AsyncSessionLocal = sessionmaker(bind=async_engine, class_=AsyncSession, expire_on_commit=False)


# async def get_session() -> AsyncGenerator[Session, None]:
#     with Session(engine) as session:
#         yield session

async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        yield session

# 插入基础数据
async def insert_initial_data():
    # session:Session =  get_session()
    try:
        # print(session)
        # print("session11")
        pass
    except Exception as e:
        # 打印e
        print("Error inserting initial data into database : " + str(e))
 
# 创建表
async def create_db_and_tables():
    # 开发解决自动创建，正式环境不要使用 使用 alembic
    if settings.APP_DEBUG:
        SQLModel.metadata.create_all(engine) 
    await insert_initial_data()


